package com.qiche.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * @author LB
 *
 * @date 2018年7月14日
 */
public class LuckyDrawUtil {
	
	public static int drawProb(List<Double> probList){

        if(null != probList && probList.size()>0){
            List<Double> orgProbList = new ArrayList<Double>(probList.size());
            for(Double prob:probList){
                //按顺序将概率添加到集合中
                orgProbList.add(prob);
            }

            return draw(orgProbList);

        }
        return -1;
    }

    public static int draw(List<Double> giftProbList){

        List<Double> sortRateList = new ArrayList<Double>();

        // 计算概率总和
        Double sumRate = 0D;
        for(Double prob : giftProbList){
            sumRate += prob;
        }

        if(sumRate != 0){
            double rate = 0D;   //概率所占比例
            for(Double prob : giftProbList){
                rate += prob;   
                // 构建一个比例区段组成的集合(避免概率和不为1)
                sortRateList.add(rate / sumRate);
            }

            // 随机生成一个随机数，并排序
            double random = Math.random();
            sortRateList.add(random);
            Collections.sort(sortRateList);

            // 返回该随机数在比例集合中的索引
            return sortRateList.indexOf(random);
        }


        return -1;
    }

    public static void main(String[] args) {
        List<Double> list = new ArrayList<Double>();
        list.add(0.1D);
        list.add(0.9D);

        for(int i=0;i<10;i++){
            int index = draw(list);
            System.out.println(index);
            //System.out.println(list.get(index));
        }
		Random rand = new Random();
		int num = rand.nextInt(7);
		System.out.println(num); 
      
    }

}
